<template>
  <div>
  <div class="activity-list">
    <el-card class="stats-card" style="height: 140px;  box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.1);
  background-color: #f5f7fa;"> <!-- 减小卡片的上下长度 -->
      <div class="stats-row">
        <div class="stats-item">
          <p class="stats-label">全部活动</p>
          <p class="stats-value">{{ totalActivities }}</p>
        </div>
        <div class="stats-dotted-line"></div> <!-- 虚线分割 -->
        <div class="stats-item">
          <p class="stats-label">未发布的</p>
          <p class="stats-value">{{ unpublishedActivities }}</p>
        </div>
        <div class="stats-dotted-line2"></div> <!-- 虚线分割 -->
        <div class="stats-item">
          <p class="stats-label">报名中</p>
          <p class="stats-value">{{ activitiesInSignupPeriod }}</p>
        </div>
        <div class="stats-dotted-line3"></div> <!-- 虚线分割 -->
        <div class="stats-item">
          <p class="stats-label">正在进行中</p>
          <p class="stats-value">{{ activitiesInProgress }}</p>
        </div>
      </div>
    </el-card>
    <div class="selectActivity" style="display: flex; justify-content: space-between; align-items: center; margin-top: 10px;">
    <el-select v-model="selectedType" clearable placeholder="选择活动类型" @change="filterActivities">
      <el-option
          v-for="activityType in activityTypes"
          :key="activityType.value"
          :label="activityType.label"
          :value="activityType.value"
      ></el-option>
    </el-select>
    <el-select v-model="selectedRelease" clearable placeholder="选择发布状态" @change="filterActivities">
      <el-option
          v-for="releaseStatus in releaseStatusOptions"
          :key="releaseStatus.value"
          :label="releaseStatus.label"
          :value="releaseStatus.value"
      ></el-option>
    </el-select>
    <el-select v-model="selectedFull" clearable placeholder="是否已满" @change="filterActivities">
      <el-option
          :key="true"
          :label="'是已满'"
          :value="true"
      ></el-option>
      <el-option
          :key="false"
          :label="'未满'"
          :value="false"
      ></el-option>
    </el-select>
      <el-button type="success" @click="goToAnotherPage">继续添加活动</el-button>
    <div class="search-container" >
      <el-input v-model="searchInput" placeholder="输入活动ID或名称" style="width: 200px;"></el-input>
      <el-button type="primary" @click="searchActivity" style="margin-left: 10px">搜索</el-button>
      <el-button @click="refreshActivities">刷新</el-button>
    </div>
    </div>
    <!-- 活动列表 -->
    <div class="activity_table" style="margin-top:0px;margin-left: -10px">
    <el-table :data="activities" style="width: 100%;background-color: transparent" >
      <el-table-column label="活动名称">
        <template slot-scope="scope">
          <el-button type="text" @click="turnActivity(scope.row.id)" style="cursor: pointer">{{ scope.row.name }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="活动类型" prop="type">
        <template slot-scope="{ row }">
          <span v-if="row.type === 1">线上</span>
          <span v-else-if="row.type === 2">校内</span>
          <span v-else-if="row.type === 3">校外</span>
        </template>
      </el-table-column>
      <el-table-column label="报名时间" width="180px">
        <template slot-scope="scope">
          <span>{{ formatDate(scope.row.activitySignStartTime) }} -- {{ formatDate(scope.row.activitySignEndTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动时间" width="180px">
        <template slot-scope="scope">
          <span>{{ formatDate(scope.row.activityConStartTime) }} -- {{ formatDate(scope.row.activityConEndTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="报名情况" v-slot="{ row }" >
        <template>
            <span :style="getReleaseStatusColor(row.IfRelease)" class="check-typeface">
          <span v-if="row.IfRelease===2">已发布(审核中)</span>
          <span v-else-if="row.IfRelease===1">草稿</span>
          <span v-else-if="row.IfRelease===3">审核通过</span>
          <span v-else-if="row.IfRelease===4">审核未通过</span>
          <span v-else-if="row.IfRelease===5">发布成功</span>
          <span v-else>未发布</span>
            </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" v-slot="{ row }">
        <template>
          <el-button type="text" @click="showDetail(row)">查看详情</el-button>
          <!-- 可以添加其他操作按钮，比如报名 -->
        </template>
      </el-table-column>
      <el-table-column label="活动状态" v-slot="{ row }" width="100px">
        <template>
          <el-button type="text" v-if="row.IfRelease===1" @click="insertIntoCheck(row)">审核</el-button>
          <el-button type="text" v-else-if="row.IfRelease===3" @click="Release(row)">发布</el-button>
          <el-button type="text" v-else-if="row.IfRelease===4" @click="Release(row)">重新发布</el-button>
          <!-- 可以添加其他操作按钮，比如报名 -->
        </template>
        <el-button type="text" v-if="row.IfRelease===2||row.IfRelease===3||row.IfRelease===4||row.IfRelease===5" @click="NotRelease(row)">撤销</el-button>
      </el-table-column>
      <el-table-column label="报名人数 / 最大人数" prop="activity_Num">
        <template slot-scope="{ row }">
          <!-- 显示活动报名人数和最大人数 -->
          {{ row.activityNum }} / {{ row.activityMaxNum }}
        </template>
      </el-table-column>
      <el-table-column label="附件下载" v-slot="{row}">
      <el-button type="text"  @click="downloadFile(row)">下载附件</el-button>
      </el-table-column>
        <el-table-column label="查看报名人员" width="120px">
        <template slot-scope="{ row }">
          <el-button @click="showEnrollments(row.id)" type="text">查看报名人员</el-button>
        </template>
      </el-table-column>
      <el-table-column label="收藏" v-slot="{row}">
        <el-button @click="collect(row)" type="text">收藏</el-button>
      </el-table-column>
      <el-table-column label="添加附件">
        <template slot-scope="{ row }">
          <el-button @click="switchUrl(row)" type="text">上传附件</el-button>
        </template>
      </el-table-column>

    </el-table>
    </div>
    <el-dialog
        title="报名人员"
        :visible.sync="enrollmentDialogVisible"
        width="50%"
    >
      <el-table :data="enrollmentData" style="width: 100%">
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column label="报名活动人" prop="name"></el-table-column>
        <el-table-column label="报名人身份">
          <template slot-scope="{ row }">
            {{ row.role === 1 ? '学生' : (row.role === 2 ? '教师' : '其他身份') }}
          </template>
        </el-table-column>
        <!-- 添加显示 school 属性的列 -->
        <el-table-column label="报名学校" prop="school"></el-table-column>
        <el-table-column label="期望省份" prop="province"></el-table-column>
        <el-table-column label="期望城市" prop="city"></el-table-column>
        <el-table-column label="期望市区" prop="district"></el-table-column>
        <el-table-column label="查看详情" >
          <template slot-scope="{ row }">
            <el-button @click="getUser(row.account)" type="text">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog
        title="上传附件"
        :visible.sync="activityUrl"
        width="400px"
        >
      <el-upload
          class="upload-demo"
          drag
          action="/api/file/upload"
          :on-success="handleAvatarSuccess"
          multiple
          style="margin-top: 20px"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <el-button @click="exitUrl()">确定</el-button>
    </el-dialog>
    <el-dialog
        title="报名人员"
        :visible.sync="userVisible"
        width="50%"
    >
      <el-table :data="[user]" style="width: 100%">
        <el-table-column label="名字" prop="name"></el-table-column>
        <el-table-column label="账号" prop="account"></el-table-column>
        <el-table-column label="性别" prop="gender"></el-table-column>
        <el-table-column label="年龄" prop="age"></el-table-column>
        <el-table-column label="手机号" prop="phone"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="角色" >{{getRoleName(user.role)}}</el-table-column>
        <el-table-column label="省份" prop="province"></el-table-column>
        <el-table-column label="城市" prop="city"></el-table-column>
        <el-table-column label="成绩" prop="grade"></el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog
        :visible.sync="dialogVisible"
        title="活动详情"
        :show-close="false"
    >
      <span>活动详情：</span>
      <p v-html="detail"></p>
      <img v-if="imageUrl" :src="imageUrl" alt="活动图片" style="max-width: 100%; height: auto;" />
      <el-button @click="downloadFile" v-if="imageUrl">下载图片</el-button>
      <el-button type="primary" @click="closeDialog">关闭</el-button>
    </el-dialog>
    <el-dialog
        id="statistics"
        title="活动统计"
        :visible="statistics"
        width="50%"
    >
      <div id="pieChart" style="width: 100%; height: 400px;"></div>
    </el-dialog>

    <!-- 可以添加其他组件，比如筛选条件、轮播图等 -->
  </div>
    </div>
</template>

<script>

import {
  getReleaseActivity,
  deleteActivity,
  getDetail,
  updateActivityStatus,
  activityRelease,
  updateActivityStatus1,
  queryActivityName, insertCheck, updateActivityStatus2
} from '../../../../api/activity'
import {mapGetters} from 'vuex'
import {getRule} from '../../../../api/rule'
import {getUserByAccount, getUserByActivity, selectStudentSchool} from '../../../../api/user'
import {getActivityUrl, insertActivityUrl} from '../../../../api/activityUrl'
import {downloadFile, queryStudentLocationById} from '../../../../api/api'
import * as echarts from 'echarts'
import {insertCollection} from '../../../../api/collect'
export default {
  name: 's-activity',
  inject: ['reload'],
  computed: {
    totalActivities () {
      return this.activities.length
    },
    unpublishedActivities () {
      return this.activities.filter(activity => activity.IfRelease === 1 || activity.IfRelease === 2 || activity.IfRelease === 3 || activity.IfRelease === 4).length
    },
    activitiesInSignupPeriod () {
      const currentDate = new Date()
      return this.activities.filter(activity => currentDate >= new Date(activity.activitySignStartTime) && currentDate <= new Date(activity.activitySignEndTime)).length
    },
    activitiesInProgress () {
      const currentDate = new Date()
      return this.activities.filter(activity => currentDate >= new Date(activity.activityConStartTime) && currentDate <= new Date(activity.activityConEndTime)).length
    },
    // 发布状态下拉选项
    releaseStatusOptions () {
      return [
        { value: '', label: '活动状态' }, // 全部选项
        { value: 1, label: '草稿' },
        { value: 2, label: '已发布(审核中)' },
        { value: 3, label: '审核通过' },
        { value: 4, label: '审核未通过' },
        { value: 5, label: '发布成功' }
      ]
    },
    activityTypes () {
      return [
        { value: '', label: '活动类型' }, // 全部选项
        { value: '1', label: '线上' },
        { value: '2', label: '校内' },
        { value: '3', label: '校外' }
      ]
    },
    ...mapGetters({
      userRole: 'user/getUserRole',
      userAccount: 'user/getUserAccount',
      userId: 'user/getUserId'
    })
  },
  data () {
    return {
      activityUpLoadId: '',
      activityUrl: false,
      statistics: false,
      asideStatus: false,
      aside_open_close: false,
      drawer: false,
      dialogVisible: false,
      detail: '',
      activityId: '',
      imageUrl: '',
      userVisible: false,
      enrollmentDialogVisible: false,
      enrollmentData: [],
      selectedType: '', // 保存选择的活动类型
      selectedRelease: '', // 保存选择的发布状态
      selectedFull: '', // 保存选择的是否已满状态
      originalActivities: [], // 保存原始活动数据
      activities: [],
      rule: {},
      searchInput: '', // 添加这行代码，用于绑定搜索框输入的值
      user: {},
      obj: '',
      url: '',
      fileName: ''
    }
  },

  created () {
    this.showActivity()
    // 调用后端接口获取活动数据，并将数据赋值给 activities
    // 例如，可以在此调用 this.getJoinActivity() 来获取已参加的活动数据
    // 通过接口获取数据并将数据赋值给 this.activities
  },
  mounted () {
    // this.$nextTick(() => {
    //   this.obj = document.getElementById('pieChart')
    // })
    // console.log(this.obj)
    // this.initDiv()
  },
  methods: {
    switchUrl (activity) {
      console.log(activity)
      this.activityUrl = true
      this.activityUpLoadId = activity.id
      console.log(this.activityUpLoadId)
    },
    exitUrl () {
      this.activityUrl = false
    },
    handleAvatarSuccess (res, file) {
      // response是服务器返回的上传成功的结果
      console.log('上传成功:', file)
      // 可以将服务器返回的信息保存到组件的数据中
      this.url = res.url
      this.fileName = file.name
      this.saveUrlToDatabase()
    },
    saveUrlToDatabase () {
      insertActivityUrl(this.activityUpLoadId, this.url, this.fileName)
        .then(response => {
          // 如果需要，处理成功的响应
          console.log('图片URL已保存到数据库')
        })
        .catch(error => {
          // 处理无法保存图片URL的错误
          console.error('保存图片URL时出错:', error)
        })
    },
    turnActivity (aid) {
      this.$router.push({name: 'activityDetail', params: {actId: aid}})
    },
    formatDate (date) {
      const newDate = new Date(date)
      const year = newDate.getFullYear()
      const month = String(newDate.getMonth() + 1).padStart(2, '0')
      const day = String(newDate.getDate()).padStart(2, '0')
      return `${year}/${month}/${day}`
    },
    goToAnotherPage () {
      this.$router.push('/main/activity/createActivity')
    },
    initDiv () {
      let char = echarts.init(document.getElementById('pieChart'))

      // 筛选 grade 区间的人数
      const gradeAbove80 = this.enrollmentData.filter(item => item.grade > 80).length
      const gradeBetween60And80 = this.enrollmentData.filter(item => item.grade >= 60 && item.grade <= 80).length
      const gradeBelow60 = this.enrollmentData.filter(item => item.grade < 60).length

      let option = {
        title: {
          text: 'Grade Distribution',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: ['Grade > 80', '60 < Grade < 80', 'Grade < 60']
        },
        series: [
          {
            name: 'Grade',
            type: 'pie',
            radius: '55%',
            center: ['50%', '60%'],
            data: [
              { value: gradeAbove80, name: 'Grade > 80' },
              { value: gradeBetween60And80, name: '60 < Grade < 80' },
              { value: gradeBelow60, name: 'Grade < 60' }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            label: {
              show: true,
              formatter: '{b} : {c} ({d}%)'
            }
          }
        ]
      }
      char.setOption(option)
    },
    // 侧边栏收缩与展开
    asidechange () {
      this.asideStatus = !this.asideStatus
      this.drawer = true
      if (this.asideStatus) {
        setTimeout(() => {
          this.aside_open_close = true
        }, 500)
      } else {
        setTimeout(() => {
          this.aside_open_close = false
        }, 500)
      }
    },
    toggleDrawer () {
      this.asideStatus = !this.asideStatus
      this.drawer = false
    },
    downloadFile () {
      getActivityUrl(this.activityId).then(urlResult => {
        console.log(urlResult)
        let obj = {
          path: urlResult[0].url
        }
        downloadFile(obj)
          .then(response => {
            // 通过创建 Blob 对象来处理下载的文件
            const blob = new Blob([response], { type: 'image/jpeg' })

            // 创建一个 URL，用于文件下载
            const downloadUrl = window.URL.createObjectURL(blob)

            // 创建一个 <a> 标签来触发下载
            const link = document.createElement('a')
            link.href = downloadUrl
            link.download = decodeURIComponent(urlResult[0].fileName)
            link.style.display = 'none'

            document.body.appendChild(link)
            link.click()

            // 清理资源
            window.URL.revokeObjectURL(downloadUrl)
            document.body.removeChild(link)
          })
          .catch(error => {
            console.error(error)
            // 处理错误
          })
      })
    },
    getRoleName (role) {
      if (role === 1) {
        return '学生'
      } else if (role === 2) {
        return '老师'
      } else if (role === 3) {
        return '学院'
      } else if (role === 4) {
        return '学校'
      } else {
        return '其他'
      }
    },
    filterActivities () {
      let filteredActivities = this.originalActivities

      if (this.selectedType) {
        const selectedTypeInt = Number(this.selectedType)
        filteredActivities = filteredActivities.filter(activity => activity.type === selectedTypeInt)
      }

      if (this.selectedRelease) {
        filteredActivities = filteredActivities.filter(activity => activity.IfRelease === this.selectedRelease)
      }

      if (this.selectedFull !== '') {
        filteredActivities = filteredActivities.filter(activity => {
          if (this.selectedFull === true) {
            return activity.activityNum === activity.activityMaxNum
          } else {
            return activity.activityNum !== activity.activityMaxNum
          }
        })
      }

      this.activities = filteredActivities
    },
    getUser (account) {
      getUserByAccount(account).then(result => {
        this.user = result
      })
      this.userVisible = true
    },
    showActivity () {
      getReleaseActivity(this.userId).then(async res => {
        this.originalActivities = res // 保存原始数据
        this.activities = res // 显示的数据同步为原始数据
        await Promise.all(
          this.activities.map(async activity => {
            this.$set(activity, 'IfRelease', activity.status)
          })
        )
      })
    },
    showDetail (activity) {
      Promise.all([getDetail(activity.id), getActivityUrl(activity.id)])
        .then(([detailResult, urlResult]) => {
          this.activityId = activity.id
          this.detail = detailResult.activityDescription
          this.imageUrl = urlResult[0].url // 获取第一个对象的 URL 属性
          this.dialogVisible = true
        })
        .catch(error => {
          // 处理错误
          console.error(error)
          this.$message.error('获取活动详情或链接时出错')
        })
    },
    closeDialog () {
      this.dialogVisible = false
    },
    searchActivity () {
      if (this.searchInput.trim() === '') {
        this.activities = this.originalActivities // 如果搜索框为空，显示所有活动
      } else {
        // 根据输入值过滤活动
        const keyword = this.searchInput.toLowerCase().trim()
        this.activities = this.originalActivities.filter(activity => {
          // 根据活动ID或名称进行模糊搜索
          return (
            activity.id.toString().includes(keyword) ||
              activity.name.toLowerCase().includes(keyword)
          )
        })
      }
    },
    refreshActivities () {
      // 刷新活动列表
      this.showActivity()
      this.searchInput = '' // 清空搜索框内容
    },
    Release (activity) {
      getRule(activity.id).then(res => {
        updateActivityStatus(activity.id).then(result => {
          this.reload()
        })
        this.rule = res
        activityRelease(this.rule, this.userId)
          .then(response => {
            console.log(response)
          })
      })
    },
    NotRelease (activity) {
      updateActivityStatus1(activity.id).then(result => {
        this.reload()
      })
      deleteActivity(activity.id).then(result => {
        this.reload()
      })
    },
    insertIntoCheck (activity) {
      getRule(activity.id).then(res => {
        if (res == null) {
          this.$message.error('请先设置活动约束')
        } else {
          queryActivityName(activity.name).then(result => {
            this.activityForm = result
            insertCheck(this.userId, this.activityForm.id)
            updateActivityStatus2(this.activityForm.id)
            this.$notify({
              message: '发送审核',
              type: 'success'
            })
          })
        }
      })
      this.reload()
    },
    getReleaseStatusColor (ifRelease) {
      switch (ifRelease) {
        case 2:
          return { color: 'orange' } // 已发布(审核中)的橙色
        case 3:
          return { color: 'lightgreen' } // 审核成功的浅绿色
        case 4:
          return { color: 'red' } // 审核未通过的红色
        case 5:
          return { color: 'darkgreen' } // 发布成功的深绿色
        case 1:
        default:
          return { color: 'grey' } // 未审核和其他情况的灰色
      }
    },
    showEnrollments (id) {
      getUserByActivity(id)
        .then(result => {
          this.enrollmentData = result
          const promises = this.enrollmentData.map(user => {
            return selectStudentSchool(user.id, id)
              .then(schoolData => {
                user.school = schoolData
                return queryStudentLocationById(user.id, id)
                  .then(res => {
                    user.province = res.province
                    user.city = res.city
                    user.district = res.district
                  })
              })
          })
          return Promise.all(promises)
        })
        .then(() => {
          console.log('All requests completed')
          console.log(this.enrollmentData) // enrollmentData 现在包含了每个用户的 school 信息和位置信息
          this.enrollmentDialogVisible = true
        })
        .catch(error => {
        // 错误处理
          console.error(error)
        })
    },
    collect (activity) {
      insertCollection(this.userId, activity.id)
        .then(result => {
          this.$message.success('收藏成功')
        })
        .catch(error => {
          this.$message.warning('重复收藏')
          console.error('收藏时出错:', error)
        })
    }
  }
}
</script>

<style scoped>
/* 侧边栏按钮样式 */
.aside_open_close{
  position: absolute;
  right: 0;
  top: 50%;
  width: 16px;
  height: 60px;
  line-height: 60px;
  color: #fff;
  background-color: #526372;
  border-radius:  6px 0 0 6px ;
  font-size: 20px;
  z-index: 1000;
  cursor: pointer;
}
.aside_open_close:hover{
  background-color: #FF8E2B;
  color: #fff;
}
.stats-card {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 10px 20px; /* 减小卡片的上下长度 */
}

.stats-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 200px; /* 调整字段之间的间距 */
  position: relative;
}

.stats-item {
  text-align: center;
}

/* 新增样式用于虚线 */
.stats-dotted-line {
  position: absolute;
  height: 100%;
  width: 1px; /* 虚线的宽度 */
  background-image: linear-gradient(to bottom, black 20%, rgba(255, 255, 255, 0) 0%);
  background-position: 50%;
  background-size: 1px 10px; /* 控制虚线的高度和间距 */
  background-repeat: repeat-y;
  top: 0;
  bottom: 0;
  left: calc(20% - 1px); /* 将虚线置于两字段之间的中间位置 */
}

.stats-dotted-line2 {
  position: absolute;
  height: 100%;
  width: 1px; /* 虚线的宽度 */
  background-image: linear-gradient(to bottom, black 20%, rgba(255, 255, 255, 0) 0%);
  background-position: 50%;
  background-size: 1px 10px; /* 控制虚线的高度和间距 */
  background-repeat: repeat-y;
  top: 0;
  bottom: 0;
  left: calc(50% - 1px); /* 将虚线置于两字段之间的中间位置 */
}
.stats-dotted-line3 {
  position: absolute;
  height: 100%;
  width: 1px; /* 虚线的宽度 */
  background-image: linear-gradient(to bottom, black 20%, rgba(255, 255, 255, 0) 0%);
  background-position: 50%;
  background-size: 1px 10px; /* 控制虚线的高度和间距 */
  background-repeat: repeat-y;
  top: 0;
  bottom: 0;
  left: calc(80% - 1px); /* 将虚线置于两字段之间的中间位置 */
}
.stats-label {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px; /* 调整字段与数字之间的间距 */
}

.stats-value {
  font-size: 32px;
  font-weight: bold;
}
.el-table th.el-table__cell{
  background-color: transparent;
}
/deep/ .el-table__header{
  background-color: transparent;
}
.el-table__header{
  background-color: transparent;
}
/*最外层透明*/
/deep/ .el-table, /deep/ .el-table__expanded-cell{
  background-color: transparent;
}
/* 表格内背景颜色 */
/deep/ .el-table th,
/deep/ .el-table tr,
/deep/ .el-table td {
  background-color: transparent;
}

.el-table::before {//去除底部白线
left: 0;
  bottom: 0;
  width: 100%;
  height: 0px;
}
.check-typeface{
  font-family: 'Arial', sans-serif;
}
/* 可以在这里添加样式 */
/* 示例中的样式是简单的示范，请根据实际需要进行样式调整 */
.activity-list {
  padding: 20px;
}
</style>
